import os
import pyaudio
import wave
from win10toast_click import ToastNotifier
import threading
import time

toast = ToastNotifier()
buffer = []
stream = None
pa = pyaudio.PyAudio()
RECORD_SECONDS = int(60 * 16000/1024)
tRecord = None
recordingEn = False


def t_record():
    global stream, pa
    stream = pa.open(format=pyaudio.paInt16,
                     channels=2,
                     rate=16000,
                     input=True,
                     frames_per_buffer=1024)

    #toast.show_toast("提示", "实时录音回放已开启")
    while recordingEn:
        try:
            data = stream.read(1024)  # 每次从流的缓存中读出数据
            buffer.append(data)
            if(len(buffer) > RECORD_SECONDS):
                buffer.pop(0)
        except Exception as e:
            print(e)
            print(repr(e))
    stream.stop_stream()  # 先把流停止
    stream.close()  # 再把流关闭
    toast.show_toast("提示", "实时录音回放已关闭")


def stop_record():
    global recordingEn, tRecord
    recordingEn = False

def start_record():
    global recordingEn, tRecord
    if recordingEn == False:
        recordingEn = True
        tRecord = threading.Thread(target=t_record, daemon=True)
        tRecord.start()

def save():
    # 创建式打开音频文件
    if not os.path.exists("D:\\data\\录音"):
        os.mkdir("D:\\data\\录音")
    wf = wave.open(time.strftime(
        "D:\\data\\录音\\%Y-%m-%d_%H-%M-%S.wav", time.localtime()), "wb")
    # 设置音频文件的属性：采样位，声道数，采样频率，缓冲区大小，必须与流的属性一致
    wf.setnchannels(2)
    wf.setsampwidth(pa.get_sample_size(pyaudio.paInt16))
    wf.setframerate(16000)
    for i in range(0, len(buffer)):
        wf.writeframes(buffer[i])  # 把读出的数据写入wf
    wf.close()  # 把声音文件关闭，否则不能播放

if __name__ == "__main__":
    start_record()
    time.sleep(25)
    save()
